package com.codimiracle.tools.outline2excel;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.IOException;
import java.time.Duration;
import java.util.List;
import java.util.Objects;

import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;

public class Spider {
    // 递归深度阈值
    private final static int DEPTH_THRESHOLD = -1;

    private ExcelGenerator generator = new ExcelGenerator();
    private int depth = 0;
    public void tree(WebDriver driver, WebDriverWait wait, WebElement element, int level) {
        if (DEPTH_THRESHOLD > 0 && depth > DEPTH_THRESHOLD) {
            return;
        }
        depth++;
        String id = element.getAttribute("id");
        boolean hasChildren = false;
        try {
            WebElement stateSwitchButton = driver.findElement(By.cssSelector("#" + id + " > .node-self > .node-state"));
            //查找当前大纲标题展开按钮
            stateSwitchButton.findElement(By.cssSelector(".closeIcon"));
            hasChildren = true;
            stateSwitchButton.click();
        } catch (Throwable throwable) {
            //试着检查是否是因为下一级大纲只有一个而失败
            try {
                hasChildren = !driver.findElements(By.cssSelector("#" + id + " > .node-children > .node-element")).isEmpty();
            } catch (Throwable throwableAnother) {
                //ignore
            }
        }
        //等待节点表示
        String titleNodeSelector = "#" + id + " > .node-self > .node-title";
        wait.until(presenceOfElementLocated(By.cssSelector(titleNodeSelector)));
        WebElement nodeTitleElement = driver.findElement(By.cssSelector(titleNodeSelector));
        String nodeTitle = nodeTitleElement.getText();
        generator.addRow(level, nodeTitle);

        if (hasChildren) {
            //开始区域合并
            generator.mergeBegin(level);
            // 处理下一大纲
            List<WebElement> children = driver.findElements(By.cssSelector("#" + id + " > .node-children > .node-element"));
            for (WebElement child : children) {
                tree(driver, wait, child, level + 1);
            }
            //处理区域合并
            generator.mergeEnd();
        }
        depth--;
    }

    public void start(String[] args) {
        System.setProperty("webdriver.chrome.driver", "integral/chromedriver.exe");
        if (args.length < 1) {
            System.out.println("请给出 processon 思维导图网址");
            return;
        }
        String processonUrl = args[0];
        if (!processonUrl.startsWith("https://www.processon.com/view/link")) {
            System.out.println("不是合法的 processon 思维导图网址");
        }

        WebDriver driver = new ChromeDriver();
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10).getSeconds());
        try {
            driver.get(processonUrl);
            driver.findElement(By.cssSelector(".viewdetail > .item.abstract")).click();
            List<WebElement> sections = driver.findElements(By.cssSelector("#outline-container > .node-element"));
            for (WebElement sectionElement : sections) {
                tree(driver, wait, sectionElement, 0);
            }
            generator.filBorder();
            generator.export("result-" + Math.round(Math.random() * 100000) + ".xls");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            driver.quit();
        }
    }
}
